<?php
/**
 * @ClassName: AddressLogic
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-11 15:44
 * @Version: V1.0.0
 */

namespace app\common\logic;

use think\facade\Cache;
use tpext\areacity\api\model\Areacity;

class AddressLogic
{
    /**
     * 获取三级地区（省市区县）
     * @param $need_cache
     * @return array|\think\response\Json
     */
    static function getThreeArea($need_cache = 1)
    {
        if ($need_cache) {
            $data = Cache::get('three_area');
            if ($data) {
                return json(["code" => 1, "msg" => "获取成功", "data" => $data]);
            }
        }

        $list = Areacity::select();

        // 提取1级
        $list1 = [];
        $code1 = [];
        foreach ($list as $key => &$item) {
            if ($item["pid"] == 0) {
                unset($list[$key]);
                $item["text"] = $item['name'];
                $item["value"] = $item['id'];
                $list1[] = $item;
                $code1[] = $item["id"];
            }
        }

        // 提取2级
        $list2 = [];
        $code2 = [];
        foreach ($list as $key2 => &$item2) {
            if (in_array($item2["pid"], $code1)) {
                unset($list[$key2]);
                $item2["text"] = $item2['name'];
                $item2["value"] = $item2['id'];
                $list2[] = $item2;
                $code2[] = $item2["id"];
            }
        }

        $list3 = [];
        $code3 = [];
        foreach ($list as $key3 => &$item3) {
            if (in_array($item3["pid"], $code2)) {
                unset($list[$key3]);
                $item3["text"] = $item3['name'];
                $item3["value"] = $item3['id'];
                $list3[] = $item3;
                $code3[] = $item3["id"];
            }
        }

        // 遍历2级和3级,处理上下级关系
        foreach ($list2 as $key1 => $city) {
            $children = [];
            foreach ($list3 as $key2 => $town) {
                if ($city["id"] == $town["pid"]) {
                    unset($list3[$key2]);
                    $children[] = $town;
                }
            }
            $list2[$key1]["children"] = $children;
        }

        // 遍历1级和2级,处理上下级关系
        foreach ($list1 as $key1 => $province) {
            $children = [];
            foreach ($list2 as $key2 => $city) {
                if ($province["id"] == $city["pid"]) {
                    unset($list2[$key2]);
                    $children[] = $city;
                }
            }
            $list1[$key1]["children"] = $children;
        }

        // 需要缓存
        if ($need_cache) {
            Cache::set("three_area", $list1);
        }
        return $list1;
    }

}